package com.dayatang.android.Activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ListView;

import com.dayatang.android.Adapter.PersonListViewAdapter;
import com.dayatang.android.Model.Person;
import com.dayatang.android.Task.BaseTask;

public class PersonListActivity extends FootCommonActivity {
	
	private ListView personListView;
	
	private PersonListViewAdapter personListViewAdapter;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AlabSetBarTitleText(getString(R.string.index_person_list));
		AlabSetContentView(R.layout.person_list_activity);
		InitListView();
	}
	
	private void InitListView(){
		personListView = (ListView) findViewById(R.id.person_listView);
		personListViewAdapter = new PersonListViewAdapter(this, getData());
		personListView.setAdapter(personListViewAdapter);
	}
	
	private List<HashMap<String, Object>> getData(){
		List<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
		String url = getServerAddress() + "/remote/person-list.action";
		try {
			String result = new BaseTask(this).execute(url).get();
			JSONArray jsonArray = new JSONArray(result);
			for (int i = 0,len = jsonArray.length(); i < len; i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Person person = new Person();
				person.setName(jsonObject.getString("name"));
				person.setOrganizationName(jsonObject.getString("organizationName"));
				person.setHolderofanOffice(jsonObject.getString("holderofanOffice"));
				person.setCellphone(jsonObject.getString("cellphone"));
				
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("ItemName", person.getName());
				map.put("ItemOrganizationName", person.getOrganizationName());
				map.put("ItemHolderofanOffice", person.getHolderofanOffice());
				map.put("ItemCellphone", person.getCellphone());
								
				listItem.add(map);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}catch (JSONException e) {
			e.printStackTrace();
		}
		return listItem;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			overridePendingTransition(R.anim.translucent_enter, R.anim.translucent_exit);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
